//
//  HYRecordProgressHUD.m
//  HYChatProject
//
//  Created by erpapa on 16/5/7.
//  Copyright © 2016年 erpapa. All rights reserved.
//

#import "HYRecordProgressHUD.h"

@interface HYRecordProgressHUD()

@property (nonatomic, strong) UIView *volumeBgView;
@property (nonatomic, strong) UIImageView *volumeImageView;
@property (nonatomic, strong) UILabel *centerLabel;
@property (nonatomic, assign) NSInteger angle;
@property (nonatomic, strong) NSTimer * myTimer;//定时器
@property (nonatomic, assign) float countDown;//倒计时,最多60秒
@property (nonatomic, assign) BOOL isLeaveSpeakBtn;
@property (nonatomic, assign) NSInteger imageIndex;

@end

@implementation HYRecordProgressHUD

+ (instancetype)sharedView {
    static dispatch_once_t once;
    static HYRecordProgressHUD *sharedView;
    dispatch_once(&once, ^ {
        sharedView = [[HYRecordProgressHUD alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        sharedView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.05];
    });
    return sharedView;
}

+ (void)showWithTitle:(NSString *)title{
    HYRecordProgressHUD *hud = [HYRecordProgressHUD sharedView];
    [hud showWithTitle:title];
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
}

- (void)showWithTitle:(NSString *)title{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CGFloat viewWidth = self.frame.size.width/2.5;
        if (!self.volumeBgView) {
            self.volumeBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewWidth, viewWidth+20)];
            self.volumeBgView.center = self.center;
            self.volumeBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
            self.volumeBgView.layer.cornerRadius = 10;
            [self addSubview:self.volumeBgView];
            self.volumeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, viewWidth - 30, viewWidth - 30)];
            self.volumeImageView.image = [UIImage imageNamed:@"voice_1"];
            [self.volumeBgView addSubview:self.volumeImageView];
        }
        self.volumeImageView.hidden = NO;
        
        self.countDown = 60;
        if (!self.centerLabel){
            self.centerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, viewWidth, viewWidth - 30)];
            self.centerLabel.backgroundColor = [UIColor clearColor];
            self.centerLabel.center = CGPointMake(self.center.x,self.center.y-20);
            self.centerLabel.text = @"";
            self.centerLabel.textAlignment = NSTextAlignmentCenter;
            self.centerLabel.font = [UIFont systemFontOfSize:79];
            self.centerLabel.textColor = [UIColor whiteColor];
            self.centerLabel.hidden = YES;
            [self addSubview:self.centerLabel];
        }
        
        if (!self.subTitleLabel){
            self.subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, viewWidth-10, 30)];
            self.subTitleLabel.center = CGPointMake(self.center.x, self.center.y+self.volumeBgView.frame.size.height*0.5-25);
            self.subTitleLabel.backgroundColor = [UIColor clearColor];
            self.subTitleLabel.layer.cornerRadius = 15.0;
            self.subTitleLabel.text = title;
            self.subTitleLabel.textAlignment = NSTextAlignmentCenter;
            self.subTitleLabel.font = [UIFont boldSystemFontOfSize:16];
            self.subTitleLabel.textColor = [UIColor whiteColor];
            [self addSubview:self.subTitleLabel];
        }
        
        if (self.myTimer){
            [self.myTimer invalidate];
            self.myTimer = nil;
        }
        
        self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startAnimation) userInfo:nil repeats:YES];
        //添加定时器
//        self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshLabelText) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
        
        [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
        animations:^{
            self.alpha = 1;
        } completion:^(BOOL finished){ }];
        [self setNeedsDisplay];
    });
}

- (void)startAnimation
{
    self.countDown -= 1;
    self.angle -= 3;
    
    if (_countDown < 7 && _countDown > 0) {
        self.volumeImageView.hidden = YES;
        self.centerLabel.hidden = NO;
        if (((int)self.countDown*10)%10 ==0) {
            self.centerLabel.text = [NSString stringWithFormat:@"%ld",(long)_countDown];
        }
    }else{
        self.volumeImageView.hidden = NO;
        self.centerLabel.hidden = YES;
//        int rand = ((int)self.countDown*10)%3;
//        self.imageIndex += (rand-1);
//        NSString * imageName = [NSString stringWithFormat:@"voice_%ld", self.imageIndex];
//        if (!self.isLeaveSpeakBtn) {
//
//            self.volumeImageView.image = [UIImage imageNamed:imageName];
//        }
    }
    //超时自动发送
    if (_countDown <= 0) {
        self.isLeaveSpeakBtn = YES;
        self.volumeImageView.image = [UIImage imageNamed:@"rc_ic_volume_wraning"];
        self.subTitleLabel.text = @"超时自动发送..";
        [self.myTimer invalidate];
    }
}

+ (void)changeSubTitle:(NSString *)title
{
    [[HYRecordProgressHUD sharedView] setState:title];
}

- (void)setState:(NSString *)str
{
    if ([str isEqualToString:@"松开手指，取消发送"]) {
        [self recordButtonTouchUpDragExit];
    }else if([str isEqualToString:@"手指上滑，取消发送"]){
        [self recordButtonTouchUpDragEnter];
    }else{
        self.subTitleLabel.text = str;
    }
}

- (void)recordButtonTouchUpDragExit {
    NSLog(@"recordButtonTouchUpDragExit");
    self.isLeaveSpeakBtn = YES;
    self.subTitleLabel.text = @"松开手指，取消发送";
    self.subTitleLabel.backgroundColor =  [UIColor colorWithRed:249/255.0 green:73/255.0 blue:68/255.0 alpha:1.0];
    self.volumeImageView.image = [UIImage imageNamed:@"rc_ic_volume_cancel"];
}

- (void)recordButtonTouchUpDragEnter {
    NSLog(@"recordButtonTouchUpDragEnter");
    self.isLeaveSpeakBtn = NO;
    self.subTitleLabel.text = @"手指上滑，取消发送";
    self.subTitleLabel.backgroundColor =  [UIColor clearColor];
    self.volumeImageView.image = [UIImage imageNamed:@"voice_1"];
}


+ (void)dismissWithTitle:(NSString *)title
{
    [[HYRecordProgressHUD sharedView] dismiss:title];
}

- (void)dismiss:(NSString *)title
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (!self.superview) return ;
        [self.myTimer invalidate];
        self.myTimer = nil;
        self.subTitleLabel.text = nil;
        self.centerLabel.text = title;
        self.centerLabel.textColor = [UIColor whiteColor];
        self.centerLabel.font = [UIFont systemFontOfSize:18];
        self.volumeImageView.hidden = YES;
        [UIView animateWithDuration:1.2 delay:0 options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished){
            if(finished) {
                [self.centerLabel removeFromSuperview];
                [self.volumeImageView removeFromSuperview];
                [self.volumeBgView removeFromSuperview];
                [self.subTitleLabel removeFromSuperview];
                [self removeFromSuperview];
                self.subTitleLabel = nil;
                self.centerLabel = nil;
                self.volumeImageView = nil;
                self.volumeBgView = nil;
            }
        }];
    });
}


+ (void)changeSoundMeter:(CGFloat)soundMeter
{
    [[HYRecordProgressHUD sharedView] changeSoundMeter:soundMeter];
}

- (void)changeSoundMeter:(CGFloat)decibels
{
    float   level;
    float   minDecibels = -80.0f;
    
    if (decibels < minDecibels) {
        level = 0.0f;
    } else if (decibels >= 0.0f) {
        level = 1.0f;
    } else {
        float   root            = 2.0f;
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        float   amp             = powf(10.0f, 0.05f * decibels);
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    NSInteger voice = level*10 + 1;
    voice = voice > 8 ? 8 : voice;
    
    self.imageIndex = voice;
    NSString * imageName = [NSString stringWithFormat:@"voice_%ld", voice];
    if (self.isLeaveSpeakBtn) {
        self.volumeImageView.image = [UIImage imageNamed:@"rc_ic_volume_cancel"];
    } else {
        self.volumeImageView.image = [UIImage imageNamed:imageName];
    }
}

@end
